package com.ie.service.before;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.MD5Util;
import com.ie.common.http.ResponseResult;
import com.ie.common.sercurity.utils.ConfigrarionBean;
import com.ie.common.sercurity.utils.JwtTokenUtil;
import com.ie.common.sercurity.utils.RedisUtil;
import com.ie.entity.BUserEntity;
import com.ie.mapper.before.BUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BUserServiceImpl extends ServiceImpl<BUserMapper, BUserEntity> implements BUserService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtUtil;
    @Autowired
    private ConfigrarionBean config;

    @Override
    public ResponseResult<Map<String, String>> register(BUserEntity bUserEntity) {
        bUserEntity.setBpwd(MD5Util.MD5(bUserEntity.getBpwd()));
        //查询邮箱是否已注册
        long n = query().eq("bemail", bUserEntity.getBemail()).count();
        if (n > 0) {//邮箱已注册
            return ResponseResult.getMessageResult(null, "A001");
        } else if (save(bUserEntity)) {//注册成功
            return ResponseResult.getMessageResult(null, "A002");
        } else {//注册失败
            return ResponseResult.getMessageResult(null, "A003");
        }
    }

    @Override
    public ResponseResult<Map<String, String>> login(BUserEntity bUserEntity) {
        // 比对验证码
        String co = (String) redisUtil.get("code");
        if (co == null || !co.equals(bUserEntity.getCode())) {// 验证码错误
            return ResponseResult.getMessageResult(null, "A000");
        }
        //验证用户名
        long res = query().eq("bemail", bUserEntity.getBemail()).count();
        if (res == 0) {//用户名不存在
            return ResponseResult.getMessageResult(null, "A001");
        }
        // 验证密码
        Map<String, String> mapparam = new HashMap<>();
        bUserEntity.setBpwd(MD5Util.MD5(bUserEntity.getBpwd()));
        mapparam.put("bemail", bUserEntity.getBemail());
        mapparam.put("bpwd", bUserEntity.getBpwd());
        List<BUserEntity> mu = query().allEq(mapparam).list();
        if (mu.size() > 0) {
            //生成buser token
            String token = jwtUtil.createToken(bUserEntity.getBemail());
            //buser用户信息保存到redis
            redisUtil.set("login_" + bUserEntity.getBemail(), bUserEntity.getBemail(), config.getRedisExpiration());
            Map<String, String> myres = new HashMap<>();
            myres.put("buserauthtoken", token);
            myres.put("bemail", bUserEntity.getBemail());
            myres.put("bid", mu.get(0).getId() + "");
            return ResponseResult.getSuccessResult(myres);
        } else {//密码错误
            return ResponseResult.getMessageResult(null, "A002");
        }

    }
}
